package com.gmlive.common.ui.dialog.detachable;

import android.app.Dialog;
import android.content.DialogInterface;
import android.view.ViewTreeObserver;

import androidx.annotation.NonNull;

/**
 * @作者: 姜志敏
 * @日期: 2019-11-25
 */
public class DetachableOnDissmisListener implements DialogInterface.OnDismissListener {
    private DialogInterface.OnDismissListener mDelegate;

    public DetachableOnDissmisListener(DialogInterface.OnDismissListener delegate) {
        mDelegate = delegate;
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        if (mDelegate != null) {
            mDelegate.onDismiss(dialog);
        }
    }

    public void clearOnDetach(@NonNull Dialog dialog) {
        if (dialog.getWindow() != null) {
            dialog.getWindow().getDecorView().getViewTreeObserver().addOnWindowAttachListener(
                    new ViewTreeObserver.OnWindowAttachListener() {
                        @Override
                        public void onWindowAttached() {
                        }

                        @Override
                        public void onWindowDetached() {
                            mDelegate = null;
                        }
                    }
            );
        }
    }
}
